<?php



class PublicAction extends CommonAction {



    public $weixin;



	public function display($temp = ''){



		$map  = "site_id = ".__SITEID__." and groupname = '".strtolower(GROUP_NAME)."' and (modelname = '".strtolower(MODULE_NAME)."' or modelname = '*') and (actionname = '".strtolower(ACTION_NAME)."' or actionname = '*')";



		$Systempages = M('Systempages') -> where($map) -> find();



		if($Systempages){



			$ModulesDB = D('Modules');



			$this->initView(); 



			echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');



			echo $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);



			echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');



		}else{



			parent::display($temp);



		}



	}



    public function _initialize() {



		$this->initCommon();



        //parent::_initialize();



        Vendor('Weixin.Weixin');



        $d['token'] = getSysVal('token');



        $d['appid'] = getSysVal('appid');



        $d['appsecret'] = getSysVal('appsecret');



        $this->weixin = new WeixinChat($d);



    }



    //会员注册



    public function reg() {



		



		$str = $this->createloginid();



		//echo $str;



		MCS(md5($str), __RELATEID__); 



		setcookie('spwd', md5($str) , time() + 1800, '/');



		$tiket = $this->weixin->createQrcode($str);



		$this->assign('tiket', $tiket);



		



		$seo['title']=getSysval('sitename').'-注册';



		$this->assign('seo', $seo);



        $this->display();



    }



    //会员登录



    public function login() {



        if ($this->memberInfo) {



            redirect(U('Member/Index/index'));



        } else {



            if ($this->is_weixin() && $this->siteInfo['is_wxLogin'] > 0) {



				if($this->siteInfo['is_wxLogin'] == 1){



					$snsapi_base = 1;



				}elseif($this->siteInfo['is_wxLogin'] == 2){



					$snsapi_base = 0;



				}



				



				/*$domain = explode(',', $this->siteInfo['domain']);



				if($domain[0] == ''){



					$domain = C('DOMAIN_MAIN');



				}*/ 



				



				



                $this->weixin->redirectGetOauthCode('http://' . $_SERVER['HTTP_HOST'] . __APP__ . "/Member/Public/getcode.html", $snsapi_base, intval($_COOKIE['aff_id']).'_and_'.base64_encode(session('jumpurl')));



            }



            if ($this->_get('type')) {



                $str = $this->createloginid();



                //echo $str;



				MCS(md5($str), __RELATEID__); 



                setcookie('spwd', md5($str) , time() + 1800, '/');



                $tiket = $this->weixin->createQrcode($str);



                $this->assign('tiket', $tiket);



            } else {



                redirect(U('Member/Public/login', array(



                    'type' => '1'



                )));



            }



        }



		$seo['title']=getSysval('sitename').'-登录';



		$this->assign('seo', $seo);



        $this->display();



    }



    private function createloginid() {



        $str = rand(100000, 999999);



        $ret = M('Member')->where(array(



            'site_id' => __RELATEID__,



            'loginid' => md5($str)



        ))->find();



        if (is_array($ret)) {



            $this->createloginid();



        }



        return $str;



    }



    //会员登出



    public function logout() {



        session('memberInfo',NULL);



        $this->success('退出成功');



    }



    //会员登录验证



    public function doLogin() {



        if (!$this->check_verify($this->_post('verify') , 'mycms')) {



            session('mycms','');



            //$this->error('验证码错误！');



        }



        if ($this->_post('password') && $this->_post('username')) {


$map = "password = '".md5($this->_post('password'))."' and site_id = '".__RELATEID__."' and (tel = '".$this->_post('username')."' or username = '".$this->_post('username')."')";
            



            



            $memberModel = D('Member');







            if ($memberModel->checkLogin($map)) {



                session('memberInfo', $memberModel->userInfo);



                //跳转到认证前页面



                if (session('jumpurl')) {



                    //$this->assign('jumpUrl',session('jumpurl'));



                    $url = session('jumpurl');



                    session('jumpurl', NULL);



                } else {



                    //$this->assign('jumpUrl',U('Index/index'));



					$memberInfo = $this->memberInfo;



                    $url = U('Index/index');



                }



                $this->success('登录成功', $url);



            } else {



                $this->error($memberModel->loginError);



            } 



        } else {



            $this->error('请输入用户和密码');



        }



    }



	



	//手机APP登录



	



	public function APPdoLogin() {



        if ($this->_post('Password') && $this->_post('UserName')) {



            $map['password'] = md5($this->_post('Password'));



            $map['_logic'] = 'and';



            $map['site_id'] = __RELATEID__;



            $map['username'] = $this->_post('UserName');



            $memberModel = D('Member');



            if ($memberModel->checkLogin($map)) {



                session('memberInfo', $memberModel->userInfo);



                $ret['UserName'] = $memberModel->userInfo['username'];



				$ret['nickname'] = $memberModel->userInfo['nickname'];



				$ret['status'] = 1;



				$ret['userType'] = $this->_post('userType');



                echo json_encode($ret);



            } else {



				$ret['status'] = 0;



				$ret['info'] = $memberModel->loginError;



				$ret['userType'] = $this->_post('userType');



				echo json_encode($ret);



            }



        } else {



			$ret['status'] = 0;



			$ret['info'] = '用户名或密码';



			$ret['userType'] = $this->_post('userType');



			echo json_encode($ret);



        }



    }



	



	//手机APP会员注册



    public function APPdoReg() {



        if ($this->_post('UserName')) {



            $_POST['site_id'] = __RELATEID__;



            $memberModel = D('Member');



            if (isset($_COOKIE['aff_id']) && intval($_COOKIE['aff_id']) > 0) {



                $_POST['pid'] = intval($_COOKIE['aff_id']);



            }



            $_POST['password'] = md5($_POST['Password']);



            $_POST['repassword'] = md5($_POST['rePassword']);



            if (!$memberModel->create()) {



                $this->error($memberModel->getError());



            }



            $user = $memberModel->where(array(



                'site_id' => __RELATEID__,



                'username' => $this->_post('UserName')



            ))->find();



            if (is_array($user)) {



				$ret['status'] = 0;



			    $ret['info'] = '该用户已经被注册';



			    echo json_encode($ret);



				exit;



            }



            $id = $memberModel->add();



            if (false === $id) {



                $this->error($memberModel->getError());



            } else {



                $data = $memberModel->where(array(



                    'id' => $id



                ))->find();



                session('memberInfo', $data);



                $ret['UserName'] = $this->_post('UserName');



				$ret['status'] = 1;



                echo json_encode($ret);



				exit;







            }



        } else {



            $ret['status'] = 0;



			$ret['info'] = '用户名不能为空';



			echo json_encode($ret);



        }



    }



	



	



	



	//会员注册



    public function dosignin() {



		if($_POST['tel']&&$_POST['password']){



			$memberDB=D('Member');



			$groupdb = M('Member_group');



			



			$_POST['site_id']=143;



			$pwd = $_POST['password'];



			$_POST['password'] = md5($_POST['password']);



			$_POST['repassword'] = md5($_POST['repassword']);



			$_POST['username'] = $_POST['tel'];



			





			//验证用户的验证码



			$vali['verifycode'] = $_POST['vali'];



			$vali['VerifyPhone'] = 0;



			$vali['tel'] = $_POST['tel'];



			$vali['site_id'] = 143;



			$memberInfo = M('Member') -> where($vali) -> find();



			if(!$memberInfo){



				$this -> error('验证码错误！');exit;



			}



			if (session('jumpurl')) {



				$this->assign('jumpUrl',session('jumpurl'));



				$jumpUrl = session('jumpurl');



				session('jumpurl',NULL);



			} else {



				$this->assign('jumpUrl',U('Index/index'));



				$jumpUrl = U('Index/index');



			}



			//if ($memberDB->create($data)) {



				$savedata = array(



				    'VerifyPhone' => 1, 



					'verifycode' => '', 



					'name'=>	$_POST['name'],



					'username' => $_POST['tel'], 



					'password' => $_POST['password'],



					'reg_time' => time()



				);



				$result = M('Member') -> where($vali) -> data($savedata) -> save();



				if (false !== $result) {



					session('memberInfo', $memberInfo);



				    D('Member')->addUser($memberInfo['id']);



					

					

					

					

					

					$this->success('注册成功！',$jumpUrl);



				} else {



					$this->error($memberDB->getError());



				}



		//	} else {



			//	$this->error($memberDB->getError());



			//}



		}else{



		    $this->error('请填写手机号、姓名！');



		}



    }



	



	



	//发送手机证验码进行验证



	public function VerifyPhoneSend(){

		

        //define('__SITEID__', 143);

		///define('__RELATEID__', 143);

		if(isset($_POST['tel'])){

            

			//发送验证码



			$tel = $this->_post('tel');



			if(M('Member') -> where(array('site_id' => 143,'VerifyPhone'=> 1, 'tel' => $tel)) -> find()){



				$this->error('该手机号码已经被使用！');exit;



			} 



			//生成一个验证码



			$data['verifycode'] = rand(123456,999999);

            $data['nickname'] = $tel;

			$data['tel'] = $tel;



			if(M('Member') -> where(array('site_id' => 143, 'tel' => $tel)) -> data($data) -> find()){



				$ret = M('Member') -> where(array('site_id' => 143, 'tel' => $tel)) -> data($data) -> save();



			}else{



				$data['site_id'] = 143;



				$ret = M('Member') -> data($data) -> add();



			}



			



			if($ret !== false){



				if(SMSSend($tel, $data['verifycode'].'　,5')){



					$this->success('发送成功，请注意查收!');exit;



				}else{



					$this->error('发送失败!');exit;



				}



			}



		}else{



			$this->error('请输入手机号码！');



		}



	}



    //微信扫描登录



    public function weixinDoLogin() {



        if ($this->_post('pass')) {



            if ($_COOKIE['spwd'] == '') {



                $this->error('登录参数出错');



                exit();



            }



            $db = M('Member');



            $ret = $db->where(array(



                /*'site_id' => __RELATEID__,*/



                'loginid' => $_COOKIE['spwd']



            ))->find();



            if (is_array($ret)) {



                //$this->success('登录成功');



                setcookie('spwd', NULL);



                $db->where(array(



                    /*'site_id' => __RELATEID__,*/



                    'openid' => $ret['openid']



                ))->data(array(



                    'loginid' => ''



                ))->save();



                $map['_logic'] = 'and';



                /*$map['site_id'] = __RELATEID__;*/



                $map['openid'] = $ret['openid'];



                $memberModel = D('Member');



                if ($memberModel->checkLogin($map)) {



                    session('memberInfo', $memberModel->userInfo);



                    //跳转到认证前页面



                    if (session('jumpurl')) {



                        //$this->assign('jumpUrl',session('jumpurl'));



                        $url = session('jumpurl');



                        session('jumpurl',NULL);



                    } else {



                       



                            $url = U('Index/index');







                    }



                    $this->success('登录成功', $url);



                } else {



                    $this->error($memberModel->loginError);



                }



            } else {



				



				



				$this->error('等待中……');



				



            }



        }



    }



    //异步登录



    public function ajaxdoLogin() {



        if ($this->_post('password') && $this->_post('username')) {



            $map['password'] = md5($this->_post('password'));



            $map['_logic'] = 'and';



            $map['site_id'] = __RELATEID__;



            $map['username'] = $this->_post('username');



            $memberModel = D('Member');



            if ($memberModel->checkLogin($map)) {



                session('memberInfo', $memberModel->userInfo);



                //跳转到认证前页面



                $this->assign('info', $memberModel->userInfo);



                $authentication_DB = M('Authentication');



				$memberInfo = $this->memberInfo;



                $authentication = $authentication_DB->where(array(



                    'member_id' => $memberInfo['id']



                ))->find();



                //dump($authentication);



                $this->assign('authentication', $authentication);



                $redata['info'] = '登录成功';



                $redata['data'] = $this->fetch();



                $redata['status'] = 1;



            } else {



                $redata['info'] = $memberModel->loginError;



                $redata['status'] = 0;



                $redata['data'] = '';



            }



        } else {



            $redata['info'] = '请填写用户名和密码';



            $redata['status'] = 0;



            $redata['data'] = '';



        }



        echo json_encode($redata);



        exit();



    }



    //检查验证码



    function check_verify($code, $id = '') {



        import('@.ORG.Verify');



        $verify = new Verify();



        return $verify->check($code, $id);



    }



	public function verify(){



		import('@.ORG.Verify');



		$Verify = new Verify();



		$Verify->entry('mycms');



	}



    //会员注册



    public function doReg() {



        if ($this->_post('username')) {



            $_POST['site_id'] = __RELATEID__;



            $memberModel = D('Member');



            if (isset($_COOKIE['aff_id']) && intval($_COOKIE['aff_id']) > 0) {



                $_POST['pid'] = intval($_COOKIE['aff_id']);



            }



            $_POST['password'] = md5($_POST['password']);



            $_POST['repassword'] = md5($_POST['repassword']);



            if (!$memberModel->create()) {



                $this->error($memberModel->getError());



            }



            $user = $memberModel->where(array(



                'site_id' => __RELATEID__,



                'username' => $this->_post('username')



            ))->find();



            if (is_array($user)) {



                $this->error('该用户已经被注册');



            }







            $id = $memberModel->add();



            if (false === $id) {



                $this->error($memberModel->getError());



            } else {



                $data = $memberModel->where(array(



                    'id' => $id



                ))->find();



                session('memberInfo', $data);



                $this->success('注册成功');







            }



        } else {



            $this->error('请填写信息');



        }



    }



    



    public function getcode() {



        $memberModel = D('Member');



		//exit($_GET['code']);



        $access_token = $this->weixin->getSnsAccessToken($_GET['code']);



		if(isset($_GET['state'])){



		    $statepid = explode('_and_', $_GET['state']);



		}else{



			$statepid = array(0,'');



		}//echo ($_GET['state']);exit;



		//dump($access_token);exit;



		if($this->siteInfo['is_wxLogin'] == 1){



			



            $login_result = $this->weixin->getSnsUserInfo($access_token['access_token'], $access_token['openid']);



		}else{



			



		    $login_result = $this->weixin->getUserInfo($access_token['openid']);



		}

		writelog1('-----------------开始---------------');

        writelog1(print_r($login_result, true));	

        writelog1($_GET['state']);

		writelog1($statepid);

		writelog1('-----------------结束---------------');

		if($login_result === false){



			return;



		}


        $where['openid'] = $login_result['openid'];



		$where['site_id'] = __RELATEID__;



		$where['status'] = 1;



        $member = $memberModel->where($where)->find();



        if ($member) {



			session('memberInfo', $member);



            //if ($member['nickname'] == '') {



                $login_result['id'] = $member['id'];



                if ($memberModel->savewx($login_result)) {



					



					//if(__SITEID__ == 113){dump($statepid);exit;}



					if($statepid[1] != ''){



						redirect(base64_decode($statepid[1]));



                        exit();



					} 



					



                    redirect(U('Member/Index/index'));



                    exit();



                }



           // }



            



            if($statepid[1] != ''){



				redirect(base64_decode($statepid[1]));



				exit();



			}else {



                redirect(U('Member/Index/index'));



            }



        } else {



            if ($login_result) {



                //会员表信息



                $user['site_id'] = __RELATEID__;



                $user['openid'] = $login_result['openid'];



                $user['nickname'] = parseWeixinName($login_result['nickname']);



                $user['sex'] = intval($login_result['sex']);



				$user['img_url'] = $login_result['headimgurl'];



				$user['reg_time']=time();



				



				



				if($user['img_url']){



					$user['is_subscribe'] = 1;



				}



				



				



                //插入会员



                $id = $memberModel->add($user);



				$data = array('username' => 'weixin'.$id);



				$data['pid'] = intval($statepid[0]);



				



				



				//清除推荐ID



				//setcookie('aff_id', '', time()-1, '/');



				$sret = $memberModel -> updatePid($id, $data['pid']);



				$memberModel -> addUser($id);

				//exit($memberModel -> getLastSql());



				//推送信息



				$userlist = $memberModel -> getUserArr($data['pid']);



				//发送通知



				



				foreach($userlist as $k => $v){



					sendWXMsg($v['openid'], "恭喜您！您的团队又增加了一名伙伴");



				}



				



                $data = $memberModel->where(array(



                    'id' => $id



                ))->find();



                session('memberInfo', $data);



               



                if ($id > 0) {



				if($statepid[1] != ''){



						redirect(base64_decode($statepid[1]));



                        exit();



					}



                    redirect(U('Member/Index/index'));



                } else {



                    $this->error('登陆错误');



                }



            }



        }



		exit('登录错误！获取信息错误，可能是接口密钥设置有误。');



        //$this->display();



    }



	



    public function getWeixinAddress() {



        Vendor('Weixin.Weixin');



        $d['token'] = getSysVal('token');



        $d['appid'] = getSysVal('appid');



        $d['appsecret'] = getSysVal('appsecret');



        $this->weixin = new WeixinChat($d);



        $this->assign('addressSign_info', $this->weixin->getSignPackage());



        //dump($this->weixin->getSignPackage());



        $this->display();



    }

	

	public function new_test(){

		

		$ret=M('Affiliatesetting')->where(array('site_id' => __SITEID__, 'status' => 1))->find();

		

		      import("@.ORG.Affiliate." . $ret['classname']);



               $class = $ret['classname'];



					

		

             $Threelevel = new $class($restult['id'], $restult['relate_id']);

			 $Threelevel->Turnover(1);

		

	}

	//这里有撤销积分，和重新计算订单积分的过程

	public function sss(){

		

		exit();

		$list=M('Integral_log')->where(' time = 1499753614')->select();

				foreach($list as $k => $v){

					if($v['member_id']==11){

					continue;	

					}

					echo 1;

					$member=M('Member')->where(' id = '.$v['member_id'])->find();

			M('Integral_log')->where(' member_id =  '.$v['member_id'])->order(' id DESC ')->limit(1)->save(array('total'=>($member['offline'])));		

				//

				//M('Member')->where('id = '.$v['member_id'])->save(array('offline'=>($v['offline']+$member['offline'])));	

				}

	

	

		

		exit();

				$list=M('Points_log')->where(' id = 583 or id = 585 ')->select();

				foreach($list as $k => $v){

				

					echo 1;

				$member=M('Points')->where(' member_id = '.$v['member_id'])->find();

				

				M('Points')->where(' member_id = '.$v['member_id'])->save(array('total'=>($member['total']-$v['total'])));

				}

				

		

				exit();

				$list=M('Integral_log')->where(' time = 1499753614')->select();

				foreach($list as $k => $v){

					if($v['member_id']==11){

					continue;	

					}

					echo 1;

				//$member=M('Member')->where(' id = '.$v['member_id'])->find();

				//M('Member')->where('id = '.$v['member_id'])->save(array('offline'=>($v['offline']+$member['offline'])));	

				}

	

	

				exit();

	 			$afflist = $payment = M('Affiliatesetting')->where(array('site_id' => 143, 'status' => 1))->select();

				$sale=M('Sale')->where(' order_id  = 2680')->find();

				

					

                foreach ($afflist as $v) {

		

                    import("@.ORG.Affiliate." . $v['classname']);



                    $class = $v['classname']; 

					

				

                    $Threelevel = new $class(2659, 143,1013);

					$Threelevel->insertlog();

					

					

                }

	

	

	

		exit();

	  $afflist = M('Affiliatesetting')->where(array('site_id' => 143, 'status' => 1))->find();

			 

			$afflist = unserialize($afflist['value']);

         

			$ponints_db = M('Points');

            $member_db = M('Member');

            $list = $ponints_db->where('total > '.$afflist['inte_rule'])->select();	

		 foreach ($list as $k => $v) {

				$num=$v['total']/$afflist['inte_rule'];

				$v['total']=$afflist['inte_rule']*(int)$num;

			

		 }

	exit();

	}

	

	

	

	public function asd(){

	

	$list=M('Member')->where('integral > 0 ')->select();

	foreach($list as $k => $v){

		

	M('Member')->where(' id = '.$v['id'])->save(array('offline'=>$v['integral']));	

	}

	

	}
	
	public function getcodeopen(){
		dump($_GET);
	}
	
	public function getAccessToken(){
		
		$url = 'https://open.weixin.qq.com/sns/explorer_broker?appid=wx11b927421f50ec1c&redirect_uri='.urlencode('http://www.ydzh99.com/Member/Public/getcodeopen.html').'&response_type=code&scope=snsapi_userinfo&state=0&connect_redirect=1
';
		header('location:'.$url);
		$url = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx11b927421f50ec1c&redirect_uri='.urlencode('http://www.ydzh99.com/Member/Public/getcodeopen.html').'&response_type=code&scope=snsapi_login&state=snsapi_login#wechat_redirect';
		//curlRequest($url);
		//header('location:'.$url);
	}
	

}



